<template>
  <el-container>
    <el-aside width="200px">
      <el-container>
        <el-header>
          <ts-select
            v-model="table"
            fileName="MetaTableReport"
            :table-width="700"
            :template="tableProps"
            @updateRow="tableChange"
          >
          </ts-select>
        </el-header>
        <el-main style="background-color: white">
          <draggable
            v-model="tableData"
            @start="onStart"
            itemKey="id"
            animation="300"
            style="display: flex; flex-direction: column"
          >
            <template #item="{ element }">
              <div class="item" :dragid="element.id">
                {{ element.name }}
              </div>
            </template>
          </draggable>
        </el-main>
      </el-container>
    </el-aside>
    <el-container>
      <el-main>
        <el-card header="">
          <template #header>
            er图设计
            <div style="float: right">
              <el-button :icon="Plus" @click="save" type="primary" plain
                >提 交</el-button
              >
            </div>
          </template>
          <div
            id="er"
            style="width: 100%; position: relative"
            tabindex="999"
          ></div>
        </el-card>
      </el-main>
    </el-container>
  </el-container>
</template>
  <script setup>
import { ref, defineModel, onMounted, computed,getCurrentInstance } from "vue";
import API from "@/api/model/meta.js";
import { ElNotification } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import ErCanvas from "@/components/tsER/index";
import tsSelect from "@/components/scSelect/index.vue";
import draggable from "vuedraggable";
import { deduplication } from "@/utils/arr";
import useTabs from "@/utils/useTabs";
const instance = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const table = ref();
const tableData = ref([]);
const dragBox = ref({});
const tableProps = {
  label: "name",
  value: "id",
};
const height = computed(() => {
  let h;
  var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  if (!iOS) {
    h = window.innerHeight;
  } else {
    h = screen.height;
  }
  return h * 0.78;
});
let er;
const width = computed(() => {
  const el = document.getElementById("er");
  return el.clientWidth;
});
onMounted(async () => {
  let res = await API.table.erDiagramDesigner.post(route.query);
  if (res.code == 200) {
    tableData.value = res.tables;
    er = new ErCanvas(document.getElementById("er"), {
      width: width.value,
      height: height.value,
      appContext:instance.appContext,
      onContextmenu(e, target) {
        console.log(target);
      },
      onSelectLine(line) {
        console.log(line, er.lines);
      },
      onSelectTable(table) {
        console.log(table);
      },
      tables: res.tables,
      lines: res.lines,
    });
  }

  // 获取div元素
  var div = document.getElementById("er");
  div.addEventListener("dragover", function (event) {
    // 阻止默认行为以允许放置
    event.preventDefault();
  });
  div.addEventListener("drop", function (event) {
    event.preventDefault();
    // 鼠标落下时的操作
    if (dragBox.value) {
      if (!er.tables.find((ele) => ele.id === dragBox.value.id)) {
        er.addTable(
          Object.assign(dragBox.value, {
            top: event.layerY,
            left: event.layerX,
            width: 100,
            height: 100,
          })
        );
        dragBox.value = null;
      }
    }
  });
});
const tableChange = async (val) => {
  let res = await API.table.detail.post({ id: val.id });
  if (res.code == 200) {
    let table = {
      id: val.id,
      name: val.name,
      fields: res.dataList.map((ele) => ({ id: ele.id, name: ele.name })),
    };
    tableData.value.push(table);
    tableData.value = deduplication(tableData.value, "id");
  }
};
const onStart = (val) => {
  let id = Number(val.item.attributes.dragid.value);
  dragBox.value = tableData.value.find((ele) => ele.id === id);
};
const save = async () => {
  let params = {
    id: route.query.id,
    tables: er.tables.map((ele) => ele.options),
    lines: er.lines.map((ele) => ele.options),
  };
  console.log(params);
  let res = await API.table.saveErDiagram.post(params);
  if (res.code == 200) {
    ElNotification.success({ message: "保存成功" });
    useTabs.close();
    router.back();
  }
};
</script>
<style lang="less" scoped>
.item {
  display: flex;
  justify-content: center;
  cursor: move;
  float: left;
  background: #fff;
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  margin: 0 15px 15px 0;
  border: 1px solid #e6e6e6;
}
</style>